package com.cjack.frenchexcel.service;

import com.cjack.frenchexcel.config.PrivateConfig;
import com.cjack.frenchexcel.dao.UserAdminDao;
import com.cjack.frenchexcel.exception.BankCardExsitException;
import com.cjack.frenchexcel.exception.BankCardNotExsitException;
import com.cjack.frenchexcel.exception.CommonException;
import com.cjack.frenchexcel.model.AdminUserModel;
import com.cjack.frenchexcel.model.ConsumerRecordConditionModel;
import com.cjack.frenchexcel.model.IntegralRecordModel;
import com.cjack.frenchexcel.model.RechargeRecordConditionModel;
import com.cjack.frenchexcel.table.AdminUserTable;
import com.cjack.frenchexcel.table.RoleTable;
import com.cjack.frenchexcel.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 后台账户管理
 * Created by root on 10/5/19
 */
@Service
public class UserAdminService {

    @Value("${file.upload.baseServerDir}")
    String baseServerDir;
    @Value("${file.upload.baseClientDir}")
    String baseClientDir;
    @Autowired
    private UserAdminDao dao;
    @Autowired
    private IntegralRecordService integralRecordService;
    @Autowired
    private ConsumerRecordService consumerRecordService;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private SendMailService sendMailService;

    //查询除了超级管理员之外的所有员工数据
    public List<AdminUserModel> findByBesideCode() {
        List<AdminUserModel> adminUserModels = ModelUtils.copyListModel(dao.findByBesideCodeOrderByJobNumberAsc(PrivateConfig.SUPER_ADMIN_CODE), AdminUserModel.class);
        // 过滤掉非公司
        List<AdminUserModel> collect = adminUserModels.stream().filter(item -> Objects.equals(item.getCompanyId(), item.getId())).collect(Collectors.toList());
        return collect;
    }

    /**
     * 返回true代表有重复
     *
     * @param model
     * @return
     */
    public boolean checkRepeat(AdminUserModel model) {
        if (!StringUtils.isEmpty(model.getJobNumber())) {
            AdminUserTable findUser = dao.findByJobNumber(model.getJobNumber());
            if (findUser != null && !findUser.getId().equals(model.getId())) {
                return true;
            }
        }
        return false;
    }
    public AdminUserTable getByJobNumber(String jobNumber) {
        return dao.findByJobNumber(jobNumber);
    }

    //处理用户发货产生的积分增加 --去掉积分转换率配置，此功能不再需要
    @Deprecated
    public void handleMoneyToIntegral(Long userId, Double money) {
        /*
        if( money == null){
            return;
        }
        List< DataDefineModel> intergalRates = dataDefineService.list( DataDefineTypeEnum.INTEGRAL_RATE);
        if( intergalRates == null || intergalRates.size() == 0){
            LOG.info( "-------查询到的积分转化率配置为空，不处理积分计算");
            return;
        }
        Integer integray = 0;
        Double rate = 0.00;
        //根据本次操作的金额，找出对应这个级别的积分转换率
        for( DataDefineModel intergalRate : intergalRates){
            if( money > Double.valueOf( intergalRate.getDataKey())){
                money = Double.valueOf( intergalRate.getDataKey());
                rate = Double.valueOf( intergalRate.getDataValue());
            }
        }
        integray = MathUtil.handleDoubleMulti( money, rate).intValue();//计算结果直接去掉小数位
        handleIntegral( userId, 1, integray);*/
    }

    /**
     * 处理积分的改变
     *
     * @param userId
     * @param type     1-增加积分，2-减少积分
     * @param integral 本次操作的积分值
     */
    public void handleIntegral(Long userId, Integer type, Integer integral) {
        AdminUserTable user = dao.getOne(userId);
        Integer beforeIntegral = user.getIntegral();
        Integer afterIntegral = 0;
        if (type.equals(1)) {
            afterIntegral = beforeIntegral + integral;
        } else if (type.equals(2)) {
            afterIntegral = beforeIntegral - integral;
        }
        user.setIntegral(afterIntegral);//保存变更之后的积分
        dao.save(user);
        IntegralRecordModel integralRecordModel = new IntegralRecordModel();
        integralRecordModel.setUserId(userId);
        integralRecordModel.setUpdateTime(new Date());
        integralRecordModel.setBeforeUpdate(beforeIntegral);
        integralRecordModel.setAfterUpdate(afterIntegral);
        integralRecordService.save(integralRecordModel);//将积分变更记录保存到数据库
    }

    public void add(AdminUserModel model) {
        AdminUserTable table;
        if (model.getId() == null) {//新增，把model里面的属性全部复制到新的table里面
            table = ModelUtils.copySignModel(model, AdminUserTable.class);
        } else {//修改，把model里面的[非空]属性赋值到数据库里面查询的table里面
            table = dao.findOne(model.getId());
            RoleTable role = table.getRole();
            ModelUtils.copySignModel(model, table);
            table.setRole(role);
        }
        dao.save(table);
    }

    public void review(AdminUserModel model) {
        AdminUserTable table = dao.findOne(model.getId());
        ModelUtils.copySignModel(model, table);
        dao.save(table);
    }

    public void del(String ids) {
        List<AdminUserTable> tables = new ArrayList<>();
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            AdminUserTable table = new AdminUserTable();
            table.setId(Long.valueOf(id));
            tables.add(table);
        }
        dao.deleteInBatch(tables);
    }

    public String resetPassword(Long id) throws CommonException {
        String newPassword = CustomerStringUtil.randomStr(6);
        AdminUserTable table = dao.getOne(id);
        table.setPassword(Md5Util.stringToMD5(newPassword));
        dao.save(table);
        return newPassword;
    }


    public AdminUserTable get(Long id) {
        return dao.getOne(id);
    }

    public void handleRepeat(AdminUserModel model) {
        //判断用户名是否重复
        List<AdminUserTable> repeatUsers = dao.findByNomAndPrenomStartingWith(model.getNom(),
                model.getPrenom().substring(0, 1));
        if (repeatUsers != null && repeatUsers.size() != 0) {
            Integer repeatNumber = 0;
            //姓后面的数字， 同名同姓，重复的第一个，姓后面的数字为1,第二个，数字为2,以此类推
            //相当于姓后面的数字，数据条数加1即可
            //新增
            if (model.getId() == null) {
                repeatNumber = repeatUsers.size();
            } else {//修改
                for (AdminUserTable repeatUser : repeatUsers) {
                    //把姓名重复的买手里面 number最大的找出来，再把它加1
                    if (repeatUser.getNomNumber() != null && repeatNumber < repeatUser.getNomNumber()) {
                        repeatNumber = repeatUser.getNomNumber();
                    }
                    if (repeatUser.getId().equals(model.getId())) {
                        return;
                    }
                }
                repeatNumber++;
            }
            model.setNomNumber(repeatNumber);
        }
    }

    /**
     * 定时任务每月1号凌晨1点执行，统计员工上月的消费/充值明细，生成excel发送到员工的邮箱
     */
    public void handleUserConsumerAndRecharge() {
        String startTime = DateFormatUtil.format(DateFormatUtil.getLastMonthZero(), DateFormatUtil.DATE_RULE_6);
        String endTime = DateFormatUtil.format(new Date(), DateFormatUtil.DATE_RULE_6);
        try {
            List<AdminUserModel> users = this.findByBesideCode();
            if (users != null && users.size() != 0) {
                for (AdminUserModel user : users) {
                    String subject = DateFormatUtil.getLastMonthStr() + "充值/消费明细汇总";
                    String content = DateFormatUtil.getLastMonthStr() + "充值/消费明细汇总";
                    ConsumerRecordConditionModel consumerRecordConditionModel = new ConsumerRecordConditionModel();
                    consumerRecordConditionModel.setImportUserId(user.getId().toString());
                    consumerRecordConditionModel.setDealStartTime(startTime);
                    consumerRecordConditionModel.setDealEndTime(endTime);
                    com.alibaba.fastjson.JSONObject consumerExportRes =
                            consumerRecordService.exportAsExcel(consumerRecordConditionModel);
                    String consumerFilePath = consumerExportRes.getString("filePath");
                    //把路径转换成服务器本地文件路径
                    consumerFilePath = FileUtils.transferClientFileUrl(consumerFilePath, baseClientDir, baseServerDir);

                    RechargeRecordConditionModel rechargeRecordModel = new RechargeRecordConditionModel();
                    rechargeRecordModel.setImportUserId(user.getId().toString());
                    rechargeRecordModel.setDealStartTime(startTime);
                    rechargeRecordModel.setDealEndTime(endTime);
                    com.alibaba.fastjson.JSONObject rechargeExportRes =
                            rechargeRecordService.exportAsExcel(rechargeRecordModel);
                    String rechargeFilePath = rechargeExportRes.getString("filePath");
                    //把路径转换成服务器本地文件路径
                    rechargeFilePath = FileUtils.transferClientFileUrl(rechargeFilePath, baseClientDir, baseServerDir);
                    sendMailService.sendAttachmentsMail(user.getEmail(), subject, content,
                            new String[]{consumerFilePath, rechargeFilePath});
                }
            }

        } catch (CommonException e) {
            e.printStackTrace();
        }
    }
}
